export class LazyLoad{
    constructor( selector ){
          this.imgs = Array.from(document.querySelectorAll( selector ));
          this.top_list = this.imgs.map( ele => this.getAbsTop(ele) );
          //BUG 只要页面不滚动，首屏图片是无法显示的; 
          this.bindEvent();
          window.dispatchEvent( new Event("scroll"));
    }
    getAbsTop( ele ){
          // 你当前的定位元素是不是body; 
          if( ele.offsetParent !== document.body){
                return ele.offsetTop + this.getAbsTop( ele.offsetParent )
          }
          return ele.offsetTop;
    }
    bindEvent(){
          // 给页面绑定卷动事件; 
          window.addEventListener("scroll" , ()=>{
                for(var i = 0 ; i < this.top_list.length; i ++){
                     if( this.top_list[i] <= scrollY + innerHeight ){
                            // 图片如果已经加载了那就直接删除掉这个图片就可以了; 
                            this.imgs[i].src = this.imgs[i].getAttribute("data-src");
                            // 删除掉对应的元素和高度信息; 
                            this.imgs.splice( i , 1 )
                            this.top_list.splice( i , 1 )
                            i --;
                      }
               }
          })    
    }

}


